package com.macro.mall.portal.service.impl;

import com.macro.mall.domain.MessageEnum;
import com.macro.mall.domain.MessageManagementAssemble;
import com.macro.mall.domain.MySession;
import com.macro.mall.mapper.MmsMessageHistoryMapper;
import com.macro.mall.mapper.MmsMessageManagementMapper;
import com.macro.mall.mapper.MmsMessageMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.service.MmsMessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class MmsMessageServiceImpl implements MmsMessageService {

    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private MmsMessageManagementMapper messageManagementMapper;
    @Autowired
    private MmsMessageMapper messageMapper;
    @Autowired
    private MmsMessageHistoryMapper messageHistoryMapper;


    @Override
    public int recordLeaveWord(Long fromId, Long toId, String msg, MessageEnum msgReadStatusNo) {
        if (StringUtils.isEmpty(msg))
            msg = "";
        Date currentDate = new Date();

        MmsMessage message = new MmsMessage();
        message.setCreateTime(currentDate);
        message.setContent(msg);
        if (0 == messageMapper.insert(message))
            return 0;
        MmsMessageManagement messageManagement = new MmsMessageManagement();
        messageManagement.setFromId(fromId);
        messageManagement.setFromType(MessageEnum.FROM_TYPE_COMMON.getValue());
        messageManagement.setToId(toId);
        messageManagement.setCorrelationId(message.getId());
        messageManagement.setCreateTime(currentDate);
        messageManagement.setSummary(msg.length() >= 20 ? msg.substring(0, 20) : msg);//摘要
        messageManagement.setStatus(MessageEnum.MSG_STATUS_NORMAL.getValue());
        messageManagement.setType(MessageEnum.MSG_TYPE_COMMON.getValue());
        messageManagement.setReadStatus(msgReadStatusNo.getValue());//已读标记

        if (0 == messageManagementMapper.insert(messageManagement))
            return 0;

        return 1;
    }

    @Override
    public long getUnreadeMsgCount(String username) {
        UmsMemberExample memberExample = new UmsMemberExample();
        memberExample.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> umsMembers = memberMapper.selectByExample(memberExample);
        if (CollectionUtils.isEmpty(umsMembers)) {
            //TODO 此处需要抛出异常
            return 0;
        }
        UmsMember member = umsMembers.get(0);

        MmsMessageManagementExample messageManagementExample = new MmsMessageManagementExample();
        MmsMessageManagementExample.Criteria criteria = messageManagementExample.createCriteria();
        criteria.andToIdEqualTo(member.getId());
        criteria.andStatusEqualTo(MessageEnum.MSG_STATUS_NORMAL.getValue());
        criteria.andReadStatusEqualTo(MessageEnum.MSG_READ_STATUS_NO.getValue());
        return messageManagementMapper.countByExample(messageManagementExample);
    }

    @Override
    public List<MessageManagementAssemble> getMoreMsgOfHistory(UmsMember selfMember, UmsMember sfMember, Integer currentPageIndex) {

        List<MessageManagementAssemble> list = new ArrayList<MessageManagementAssemble>();
        MmsMessageManagementExample messageManagementExample = new MmsMessageManagementExample();
        MmsMessageManagementExample.Criteria managementExampleCriteria = messageManagementExample.createCriteria();
        MmsMessageManagementExample.Criteria managementExampleCriteria2 = messageManagementExample.createCriteria();
        //平台消息
        if (sfMember == null) {
            managementExampleCriteria.andFromIdEqualTo(0L);
            managementExampleCriteria.andFromTypeEqualTo(MessageEnum.FROM_TYPE_PLATFORM.getValue());
            managementExampleCriteria.andToIdEqualTo(selfMember.getId());
            messageManagementExample.setOrderByClause(" create_time DESC LIMIT "+(currentPageIndex-1) * 30 +", "+30);

        } else {//私信聊天
            managementExampleCriteria.andFromIdEqualTo(selfMember.getId()).andToIdEqualTo(sfMember.getId()).andFromTypeEqualTo(MessageEnum.FROM_TYPE_COMMON.getValue());
            managementExampleCriteria2.andFromIdEqualTo(sfMember.getId()).andToIdEqualTo(selfMember.getId()).andFromTypeEqualTo(MessageEnum.FROM_TYPE_COMMON.getValue());
            messageManagementExample.or(managementExampleCriteria2);
            messageManagementExample.setOrderByClause(" create_time DESC LIMIT "+(currentPageIndex-1) * 30 +", "+30);

        }
        List<MmsMessageManagement> mmsMessageManagements = messageManagementMapper.selectByExample(messageManagementExample);

        if (CollectionUtils.isEmpty(mmsMessageManagements)) {
            return list;
        }

        List<Long> messageIds = new ArrayList<>();
        List<Long> messageHistoryIds = new ArrayList<>();

        for (MmsMessageManagement messageManagement : mmsMessageManagements) {
            if (messageManagement.getStatus() == MessageEnum.MSG_STATUS_NORMAL.getValue()) {
                messageIds.add(messageManagement.getCorrelationId());
            } else {
                messageHistoryIds.add(messageManagement.getCorrelationId());
            }
        }

        MmsMessageExample messageExample = new MmsMessageExample();
        List<MmsMessage> mmsMessages = new ArrayList<>();

        if (!CollectionUtils.isEmpty(messageIds)) {
            messageExample.createCriteria().andIdIn(messageIds);
            mmsMessages = messageMapper.selectByExample(messageExample);
        }

        MmsMessageHistoryExample mmsMessageHistoryExample = new MmsMessageHistoryExample();
        List<MmsMessageHistory> mmsMessageHistories = new ArrayList<>();
        if (!CollectionUtils.isEmpty(messageHistoryIds)) {
            mmsMessageHistoryExample.createCriteria().andIdIn(messageHistoryIds);
            mmsMessageHistories = messageHistoryMapper.selectByExample(mmsMessageHistoryExample);
        }

        for (MmsMessageManagement messageManagement : mmsMessageManagements) {
            MessageManagementAssemble messageManagementAssemble = new MessageManagementAssemble();
            messageManagementAssemble.setCreateTime(messageManagement.getCreateTime());
            messageManagementAssemble.setFromId(messageManagement.getFromId());
            if (sfMember == null) {//平台消息
                messageManagementAssemble.setFromUsername("系统");
            } else {
                if (messageManagement.getFromId() == selfMember.getId()){
                    messageManagementAssemble.setFromUsername(selfMember.getNickname());
                } else {
                    messageManagementAssemble.setFromUsername(sfMember.getNickname());
                }
            }
            messageManagementAssemble.setToId(messageManagement.getToId());
            if (messageManagement.getToId() == selfMember.getId()){
                messageManagementAssemble.setFromUsername(selfMember.getNickname());
            } else {
                messageManagementAssemble.setFromUsername(sfMember.getNickname());
            }

            if (messageManagement.getStatus() == MessageEnum.MSG_STATUS_NORMAL.getValue()) {
                for (int i = 0; i < mmsMessages.size(); i++) {
                    if (messageManagement.getCorrelationId() == mmsMessages.get(i).getId()) {
                        messageManagementAssemble.setContent(mmsMessages.get(i).getContent());
                        break;
                    }
                }
            } else {//历史消息
                for (int j = 0; j < mmsMessageHistories.size(); j++) {
                    if (messageManagement.getCorrelationId() == mmsMessageHistories.get(j).getId()) {
                        messageManagementAssemble.setContent(mmsMessageHistories.get(j).getContent());
                        break;
                    }
                }
            }

            list.add(messageManagementAssemble);
        }

        return list;
    }

    @Override
    public List<MySession> getSessionList(String username) {

        List<MySession> list = new ArrayList<>();

        UmsMember selfMember = getMemberByUsername(username);

        if (null == selfMember)
            return list;
//TODO 待改进
        MmsMessageManagementExample example = new MmsMessageManagementExample();
        example.createCriteria().andToIdEqualTo(selfMember.getId());
//                .andReadStatusEqualTo(MessageEnum.MSG_READ_STATUS_NO.getValue());

        List<MmsMessageManagement> messageManagements = messageManagementMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(messageManagements))
            return list;

        //去重
        List<MmsMessageManagement> messageManagements2 = new ArrayList<MmsMessageManagement>();
        Set<Long> fromIdSet = new HashSet<Long>();
        for (MmsMessageManagement mm : messageManagements ) {
            if (!fromIdSet.contains(mm.getFromId())) {
                fromIdSet.add(mm.getFromId());
                messageManagements2.add(mm);
            }
        }

        for (MmsMessageManagement mm : messageManagements2 ) {
            MySession mySession = new MySession();
            //获取未读消息数量
            MmsMessageManagementExample mme = new MmsMessageManagementExample();
            mme.createCriteria().andFromIdEqualTo(mm.getFromId())
                    .andToIdEqualTo(mm.getToId())
                    .andReadStatusEqualTo(MessageEnum.MSG_READ_STATUS_NO.getValue());
            long count = messageManagementMapper.countByExample(mme);
            mySession.setCount(count);

            if (mm.getFromType() == MessageEnum.FROM_TYPE_PLATFORM.getValue()) {
                mySession.setOppositeId(mm.getFromId());
                mySession.setOppositeType(1);
                mySession.setOppositeUsername("0");
                mySession.setIcon("");
                mySession.setNickname("系统消息");
            } else {
                UmsMember fromMember = memberMapper.selectByPrimaryKey(mm.getFromId());
                mySession.setOppositeId(fromMember.getId());
                mySession.setOppositeType(0);
                mySession.setOppositeUsername(fromMember.getUsername());
                mySession.setIcon(fromMember.getIcon());
                mySession.setNickname(fromMember.getNickname());
            }

            list.add(mySession);
        }

        return list;
    }

    @Override
    public List<MessageManagementAssemble> getUnreadMstList(long selfId, long oppositeId) {

        List<MessageManagementAssemble> list = new ArrayList<>();

        MmsMessageManagementExample example = new MmsMessageManagementExample();
        example.createCriteria().andToIdEqualTo(selfId)
                .andFromIdEqualTo(oppositeId)
                .andReadStatusEqualTo(MessageEnum.MSG_READ_STATUS_NO.getValue());
        example.setOrderByClause(" ORDER BY CREATE_TIME DESC");

        List<MmsMessageManagement> messageManagements = messageManagementMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(messageManagements))
            return list;

        List<Long> ids = new ArrayList<>();
        for (MmsMessageManagement mm : messageManagements
             ) {
            ids.add(mm.getCorrelationId());
        }

        MmsMessageExample messageExample = new MmsMessageExample();
        messageExample.createCriteria().andIdIn(ids);

        List<MmsMessage> mmsMessages = messageMapper.selectByExample(messageExample);
        if (CollectionUtils.isEmpty(mmsMessages))
            return list;

        for (MmsMessageManagement mm : messageManagements) {

            MessageManagementAssemble mma = new MessageManagementAssemble();
            mma.setCreateTime(mm.getCreateTime());
            mma.setFromId(mm.getFromId());
            mma.setToId(mm.getToId());
            mma.setToUsername("");
            mma.setFromUsername("");

            for (MmsMessage message : mmsMessages) {
                if (mm.getCorrelationId() == message.getId()) {
                    mma.setContent(message.getContent());
                    break;
                }
            }
            list.add(mma);
        }

        //变更消息的状态为已读状态
        for (MmsMessageManagement mm : messageManagements) {
            mm.setReadStatus(MessageEnum.MSG_READ_STATUS_YES.getValue());
            messageManagementMapper.updateByPrimaryKey(mm);
        }

        return list;
    }

    /**
     * 通过用户名获取用户
     * @param username
     * @return
     */
    private UmsMember getMemberByUsername (String username) {
        if (StringUtils.isEmpty(username))
            return null;
        UmsMemberExample memberExample = new UmsMemberExample();
        memberExample.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> umsMembers = memberMapper.selectByExample(memberExample);

        if (CollectionUtils.isEmpty(umsMembers))
            return null;

        return umsMembers.get(0);
    }
}
